<?php

require_once("View/View/PageView.php");
require_once("Exercises/View/ExercisesView.php");
require_once("Exercises/Model/ExerciseModel.php");
require_once("login/src/Model/LoginValidation.php");

class ExersicesController
{
	private $pageView;
	private $exerciseModel;
	private $exersicesView;
	private $loginvalidation;

	public function __construct()
	{
		$this->pageView = new PageView();
		$this->exersicesView = new ExersicesView();
		$this->loginvalidation = new LoginValidation();
		$this->exerciseModel = new ExerciseModel($this->exersicesView->getIdToEdit());
	}	

	public function areWeLoggedIn()
	{
		if(!$this->loginvalidation->weAreLoggedIn())
		{
			header("Location:index.php");
		}
	}

	public function getPage()
	{ $this->exerciseModel->resetErrorMessages();
		if($this->exersicesView->checkIfAddNewExercise())
		{	
			$this->addNewExercise();
		}
		if($this->exersicesView->removeExerciseOnID())
		{
			$this->removeExercise(); 
		}
		if($this->exersicesView->editedExercise())
		{
			$this->editExercise(); // GANSKA LIK addNewExercise.
		}
		$html = $this->exersicesView->getExercisesPage();
		$html = $this->pageView->getHtmlPage("Övningar - Träningsdagboken", "", $html);
		return $html;
	}

	//TODO: KOLLA KOMMENTARER UNDER:
	private function removeExercise()
	{
		$exerciseID = $this->exersicesView->getIdToRemove();
		$this->exerciseModel->ValidateAndDeleteExercise($exerciseID);
		header("Location:Exercises.php");
	}

	private function editExercise()
	{
		if($this->checkIfPost())
		{
			if($this->exersicesView->finishedEdit())
			{
				$mouscleGroupID = $this->exersicesView->getEditMuscleGroupID();
				$eName = $this->exersicesView->getEditExerciseName();
    			$eDescription = $this->exersicesView->getEditExerciseDescription();
    			$exerciseID = $this->exersicesView->getEditID();

    			if($this->exerciseModel->ValidateExercise($mouscleGroupID, $eName, $eDescription, $exerciseID))
    			{	
    				$this->exerciseModel->CreateAndSaveExercise($mouscleGroupID, $eName, $eDescription, $exerciseID);
    			}
			}
		}
	}


	private function checkIfPost()
	{
		if($_SERVER['REQUEST_METHOD'] == 'POST')
		{
			return true;
		}
		return false;
	}


	private function addNewExercise()
	{

		if($this->checkIfPost())
		{
			if($this->exersicesView->checkIfAddNewExercise())
			{
				$mouscleGroupID = $this->exersicesView->getNewMuscleGroupID();
				$eName = $this->exersicesView->getNewExerciseName();
    			$eDescription = $this->exersicesView->getNewExerciseDescription();

    			if($this->exerciseModel->ValidateExercise($mouscleGroupID, $eName, $eDescription))
    			{
    				$this->exerciseModel->CreateAndSaveExercise($mouscleGroupID, $eName, $eDescription);
    			}
			}
		}
	}

}